//
//  SGHttpTool.m
//  post
//
//  Created by liu chao on 15/10/8.
//  Copyright (c) 2015年 liu chao. All rights reserved.
//

#import "SGHttpTool.h"
#import "MJExtension.h"
#import "NSString+JSON.h"
#import "AFAppDotNetAPIClient.h"
#import "LogInViewController.h"

@implementation SGHttpTool

+ (void)POST:(SGParameter *)parameter sucess:(HttpRequestSuccess)success failure:(HttpRequestFailed)failure {
    [self POST:[OtherNetworking sharedManager].STRURL parameter:parameter sucess:success failure:failure];
}

+ (void)POST:(NSString *)url
   parameter:(SGParameter *)parameter
      sucess:(HttpRequestSuccess)success
     failure:(HttpRequestFailed)failure {
    
    AFAppDotNetAPIClient *manager = [AFAppDotNetAPIClient sharedClient];

//充值接口需加
    if ([url containsString:@"g=Client&m=pay&a=ybpay"]) {
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    
    //添加header
    NSDictionary *headerFieldValueDictionary = parameter.header.mj_keyValues;
    
    
    NSLog(@"header == ---------- \n %@ \n--------",headerFieldValueDictionary);
    
    if (headerFieldValueDictionary != nil) {
        for (NSString *httpHeaderField in headerFieldValueDictionary.allKeys) {
            NSString *value = headerFieldValueDictionary[httpHeaderField];
            [manager.requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
        }
    }
    
//    NSLog(@"接口-->>>>>>%@\n请求header :%@",url,manager.requestSerializer.HTTPRequestHeaders);
    
    //对body做处理   mutableHTTPRequestHeaders
    NSDictionary *body = parameter.body;
    body = [self paramTokenFromDic:body];
    
    
    NSLog(@"-->>>>>>%@\nbody--%@", url,body);
    
    
    [manager POST:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
//        NSDictionary *allHeaders = response.allHeaderFields;
//        NSLog(@"响应header:%@", allHeaders);
//        NSLog(@"接口===%@\n\n\n%@\n\n\n",url,responseObject);

        
        if ([responseObject[@"status"] intValue] == 201) {
            
            [ZYUserManager clearUserInfo];
            LogInViewController *lvc = [[LogInViewController alloc]init];
            UINavigationController *ncv = [[UINavigationController alloc]initWithRootViewController:lvc];
            [UIApplication sharedApplication].keyWindow.rootViewController = ncv;
        
        }else{
            success(responseObject);
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error %@", error);
        failure(error);
    }];
}




+ (void)POSTURL:(NSString *)url sucess:(HttpRequestSuccess)success failure:(HttpRequestFailed)failure {
    
    AFAppDotNetAPIClient *manager = [AFAppDotNetAPIClient sharedClient];
    NSLog(@"url: %@", url);
    [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"error %@", error);
        failure(error);
    }];
}

#pragma mark - post

+ (__kindof NSURLSessionTask *)post:(SGParameter *)parameter
                             sucess:(HttpRequestSuccess)success
                            failure:(HttpRequestFailed)failure {
    
    return [self post:parameter modified:nil sucess:success failure:failure];
}

+ (__kindof NSURLSessionTask *)post:(SGParameter *)parameter
                           modified:(HttpRequestModified)modified
                             sucess:(HttpRequestSuccess)success
                            failure:(HttpRequestFailed)failure {
    
    AFAppDotNetAPIClient *manager = [AFAppDotNetAPIClient sharedClient];
    
//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    dict[@"jsonData"] = parameter.mj_JSONString;
    
    //添加header
    NSDictionary *headerFieldValueDictionary = parameter.header.mj_keyValues;
    if (headerFieldValueDictionary != nil) {
        for (NSString *httpHeaderField in headerFieldValueDictionary.allKeys) {
            NSString *value = headerFieldValueDictionary[httpHeaderField];
            [manager.requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
        }
    }
    //对body做处理
    NSDictionary *body = parameter.body;
    body = [self paramTokenFromDic:body];
    
    
    
    
    NSURLSessionTask *sessionTask = [manager POST:[OtherNetworking sharedManager].STRURL parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (modified) {
            modified(responseObject);
        }
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
    
    return sessionTask;
}

+ (__kindof NSURLSessionTask *)post:(SGParameter *)parameter
                           modified:(HttpRequestModified)modified
                              cache:(HttpRequestCache)cache
                             sucess:(HttpRequestSuccess)success
                            failure:(HttpRequestFailed)failure {
    
    AFAppDotNetAPIClient *manager = [AFAppDotNetAPIClient sharedClient];
//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    dict[@"jsonData"] = parameter.mj_JSONString;
    
    //添加header
    NSDictionary *headerFieldValueDictionary = parameter.header.mj_keyValues;
    if (headerFieldValueDictionary != nil) {
        for (NSString *httpHeaderField in headerFieldValueDictionary.allKeys) {
            NSString *value = headerFieldValueDictionary[httpHeaderField];
            [manager.requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
        }
    }
    //对body做处理
    NSDictionary *body = parameter.body;
    body = [self paramTokenFromDic:body];
    
    
    NSURLSessionTask *sessionTask = [manager POST:[OtherNetworking sharedManager].STRURL parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (modified) {
            modified(responseObject);
        }
        if (cache) {
            cache(responseObject);
        }
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
    
    return sessionTask;
}


#pragma mark - 添加加密字符串
+ (NSDictionary *)paramTokenFromDic:(NSDictionary *)param{
    NSMutableDictionary *params = param.mutableCopy;
    NSArray *keyArray = [params allKeys];
    NSArray *sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
    
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortString in sortArray) {
        [valueArray addObject:[params objectForKey:sortString]];
    }
    
    NSMutableArray *signArray = [NSMutableArray array];
    for (int i = 0; i < sortArray.count; i++) {
        NSString *keyValueStr = [NSString stringWithFormat:@"%@%@",sortArray[i],valueArray[i]];
        [signArray addObject:keyValueStr];
    }
    NSString *sign = [signArray componentsJoinedByString:@""];
    sign =  [sign stringByAppendingString:@"avjdsbvjkdsvk"];
//    NSLog(@"%@-%@",sign,sign.pm_stringFromMD5);
    [params setObject:sign.pm_stringFromMD5 forKey:@"paramToken"];
    return params.copy;
}

@end
